package com.liang.servlet.user;

import com.liang.pojo.User;
import com.liang.service.user.UserService;
import com.liang.service.user.UserServiceImpl;
import com.liang.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    //Servlet：控制层，调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取登录用户的用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //查询数据库是否存在该用户，调用业务层
        UserService userService = new UserServiceImpl();
        User user = null;
        try {
            user = userService.login(userCode, userPassword);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(user!=null && userPassword.equals(user.getUserPassword())){
            //查到了
            //将用户信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else{
            //没查到
            //转发回登录页面，并且提示用户名或密码错误
            req.setAttribute("error","用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
